package gallery;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.View;

import com.diegocarloslima.byakugallery.lib.GalleryViewPager;
import com.laoxinwen.app.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import common.BaseActivity;
import util.IntentUtil;
import util.bitmap.FileUtil;

@SuppressLint("DefaultLocale")
public class BasePicViewerActivity extends BaseActivity {
    public static final String INTENT_KEY_PATH_LIST = "a";
    public static final String INTENT_KEY_URL_LIST = "b";
    public static final String INTENT_KEY_INDEX = "c";
    public static final String INTENT_KEY_RESULT_PATH_LIST = "a";
    private GalleryAdapter adapter;
    private int currentPicIndex;
    private DotView dotView;
    private GalleryViewPager gallery;
    private SparseArray<GalleryFragment> map = new SparseArray<GalleryFragment>();
    private ArrayList<String> pathList;
    private ArrayList<String> urlList;    protected ArrayList<String> getPathList() {
        return pathList;
    }

    public static Intent getIntent(int index, ArrayList<String> urlList, Context context) {
        Intent it = new Intent(context, BasePicViewerActivity.class);
        it.putExtra(INTENT_KEY_INDEX, index);
        it.putExtra(INTENT_KEY_URL_LIST, urlList);
        return it;
    }

    private class GalleryAdapter extends FragmentStatePagerAdapter {
        GalleryAdapter() {
            super(getSupportFragmentManager());
        }

        @Override
        public int getCount() {
            return pathList.size();
        }

        @Override
        public Fragment getItem(int position) {
            GalleryFragment fg = new GalleryFragment();

            fg.setImagePath(pathList.get(position));
            if (null != urlList) {
                fg.setImageUrl(urlList.get(position));
            }
            if (position == currentPicIndex) {
                fg.setGifPause(false);
            } else {
                fg.setGifPause(true);
            }
            map.put(position, fg);
            return fg;
        }


    }    protected int getCurrentPicIndex() {
        return currentPicIndex;
    }

    //	private OnClickListener shareListener = new View.OnClickListener() {
    //		public void onClick(View v) {
    //			Intent it = new Intent();
    //			it.setAction(Intent.ACTION_SEND);
    //			it.setType("image/jpg");
    //			it.putExtra(Intent.EXTRA_STREAM, Uri.parse("module.cloud.file://"+pathList.get(currentPicIndex)));
    //			Intent intent = Intent.createChooser(it, "来自igap动态分享");
    //			if(null!=intent){
    //				startActivity(intent);
    //			}
    //		}
    //	};
    //	private OnClickListener saveListener = new OnClickListener() {
    //		private final Uri STORAGE_URI = Images.Media.EXTERNAL_CONTENT_URI;
    //		private final String IMAGE_MIME_TYPE = "image/png";
    //		@Override
    //		public void onClick(View v) {
    //			// TODO Auto-generated method stub
    //			ContentValues values = new ContentValues(2);
    //			values.put(Images.Media.MIME_TYPE, IMAGE_MIME_TYPE);
    //			values.put(Images.Media.DATA, pathList.get(currentPicIndex));
    //			Uri dataUri = getContentResolver().insert(STORAGE_URI, values);
    //			//TODO 拷贝图片到Camera或DCMI文件夹下的H诶H诶Pic目录下
    //			String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/HeiheiPic/";
    //			BitmapFactory.Options opts = new BitmapFactory.Options();
    //			opts.inJustDecodeBounds = true;
    //			BitmapFactory.decodeFile(pathList.get(currentPicIndex), opts);
    //			path += Long.toString(System.currentTimeMillis()/1000, 36);
    //			if(opts.outMimeType.toUpperCase().contains("GIF")){
    //				path += ".gif";
    //			}else if(opts.outMimeType.toUpperCase().contains("IMAGE")){
    //				path += ".jpg";
    //			}
    //			try {
    //				fileCopy(pathList.get(currentPicIndex),path);
    //				ToastUtil.toast(BasePicViewerActivity.this, "保存成功", Toast.LENGTH_SHORT);
    //			} catch (IOException e) {
    //				e.printStackTrace();
    //				ToastUtil.toast(BasePicViewerActivity.this, "抱歉保存失败", Toast.LENGTH_SHORT);
    //			}
    //
    //		}

    //		private void fileCopy(String srcPath, String targetPath) throws IOException{
    //			File f = new File(targetPath);
    //			if(!f.getParentFile().exists()){
    //				f.getParentFile().mkdirs();
    //			}
    //			FileInputStream fis = new FileInputStream(srcPath);
    //			FileOutputStream fos = new FileOutputStream(targetPath);
    //			byte[] buffer = new byte[1024*50];
    //			int n = 0;
    //			while(-1!=(n=fis.read(buffer))){
    //				fos.write(buffer, 0, n);
    //			}
    //			fis.close();
    //			fos.close();
    //		}
    //	};

    protected ArrayList<String> getUrlList() {
        return urlList;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic_viewer);
        gallery = (GalleryViewPager) findViewById(R.id.gallery_view_pager_sample_gallery);
        dotView = (DotView) findViewById(R.id.dotview);
        pathList = getIntent().getStringArrayListExtra(INTENT_KEY_PATH_LIST);
        if (null == pathList) {
            urlList = getIntent().getStringArrayListExtra(INTENT_KEY_URL_LIST);
            pathList = new ArrayList<String>();
            for (String url : urlList) {
                pathList.add(FileUtil.getImgPath(url));
            }
        }
        if (urlList.size() == 1) {
            dotView.setVisibility(View.GONE);
        }
        dotView.set(pathList.size(), Color.GRAY, Color.WHITE);
        adapter = new GalleryAdapter();
        gallery.setAdapter(adapter);
        gallery.setOffscreenPageLimit(1);
        gallery.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageSelected(int arg0) {
                currentPicIndex = arg0;
                dotView.setCurIndex(currentPicIndex);
                GalleryFragment f = map.get(arg0);
                if (null != f) {
                    f.setGifPause(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        currentPicIndex = getIntent().getIntExtra(INTENT_KEY_INDEX, 0);
        gallery.setCurrentItem(currentPicIndex);
        dotView.setCurIndex(currentPicIndex);
    }


    //	protected void remove(int index){
    //		pathList.remove(index);
    //		if(pathList.isEmpty()){
    //			finish();
    //		}else{
    //			dotView.set(pathList.size(), Color.GRAY, Color.RED);
    //			gallery.setAdapter(adapter);
    //			if(currentPicIndex==pathList.size()){
    //				currentPicIndex--;
    //			}
    //			gallery.setCurrentItem(currentPicIndex);
    //			dotView.setCurIndex(currentPicIndex);
    //		}
    //
    //	}




    @Override
    public void finish() {
        setResult(RESULT_OK, getIntent().putStringArrayListExtra(INTENT_KEY_RESULT_PATH_LIST, pathList));
        super.finish();
    }




    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_save:
                save();
                break;
            case R.id.bt_share:
                try {
                    String path = pathList.get(currentPicIndex);
                    startActivity(IntentUtil.getSharePicAndText("凿音", path));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void save() {
        File targetFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Zaoyin/" + System.currentTimeMillis() + ".jpg");
        targetFile.getParentFile().mkdirs();
        File file = new File(getPathList().get(getCurrentPicIndex()));
        if (file.exists()) {
            try {
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(targetFile);
                byte[] buffer = new byte[1024 * 1024];
                int n = 0;
                while (-1 != (n = fis.read(buffer))) {
                    fos.write(buffer, 0, n);
                }
                fis.close();
                fos.close();
                addMediaStore(targetFile);
                showToast("保存成功:" + targetFile.getParentFile());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void addMediaStore(File targetFile) {
        ContentResolver resolver = this.getContentResolver();
        ContentValues newValues = new ContentValues(5);
        newValues.put(MediaStore.Images.Media.DISPLAY_NAME, targetFile.getName());
        newValues.put(MediaStore.Images.Media.DATA, targetFile.getPath());
        newValues.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000);
        newValues.put(MediaStore.Images.Media.SIZE, targetFile.length());
        newValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, newValues);
    }
}
